/**
 * Copyright (C) 2013 Inera AB (http://www.inera.se)
 *
 * This file is part of Inera Certificate Proxy (http://code.google.com/p/inera-certificate-proxy).
 *
 * Inera Certificate Proxy is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Inera Certificate Proxy is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package se.inera.certificate.proxy.mappings.local;

import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.Collections.enumeration;
import static java.util.Collections.list;

/**
 *
 */
public class LocalRequestWrapper extends HttpServletRequestWrapper {

    private ListMultimap<String, String> headers = LinkedListMultimap.create();

    public LocalRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    void addHeader(String name, String value) {
        headers.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        List<String> values =  headers.get(name);
        if (!values.isEmpty()) {
            return values.get(0);
        }
        return super.getHeader(name);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        List<String> values = newArrayList(headers.get(name));
        if (values.isEmpty()) {
            Enumeration<String> e = super.getHeaders(name);
            if (e != null) {
                values.addAll(list(e));
            }
        }
        return enumeration(values);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        Set<String> keys = newHashSet(headers.keySet());
        Enumeration<String> e = super.getHeaderNames();
        if (e != null) {
            keys.addAll(list(e));
        }
        return enumeration(keys);
    }
}
